<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-16 16:44:37
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 17:17:32
-->
<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="50%">
    <el-form :model="params" class="demo-form-inline" ref="params" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="'按钮名称'" prop="menuName">
            <el-input v-model="params.menuName" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'按钮英文名称'" prop="menuNameEn">
            <el-input v-model="params.menuNameEn" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'权限标识'" prop="perms">
            <el-input v-model="params.perms" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'显示排序'" prop="sort">
            <el-input-number size="small" v-model="params.sort" controls-position="right" :min="1"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="'关联接口'" prop="apiIds">
            <x-page-transfer
              ref="apiTransfer"
              :from-data="tableData"
              :to-data="toData"
              :title="['接口列表', '已选接口']"
              :attr-option="attrOptions"
              :paginationData="pagination"
              @on-change="handleTableChange"
            >
              <template #leftTitle>
                <moudle-swtich
                  ref="moudleSwtichComponents"
                  :options="treeOptions"
                  :defaultProps="attrOptions"
                  :current-node="currentNode"
                  @handleResetNode="handleResetNode"
                />
              </template>
            </x-page-transfer>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button type="primary" @click="handleSubmit" :loading="btnloading">
        {{ $t('common.confirm') }}
      </el-button>
      <!-- <el-button v-if="'id' in params" type="danger" @click="handleDeleteOrg"> 删除 </el-button> -->
    </span>
  </x-dialog>
</template>
<script lang="jsx">
  import { omit, throttle, buttonIcons, TableListMixin } from '@package/utils'
  // import { } from '@/common/mixins'
  import { apiPostAddMenu, apiPostEditMenu } from '../api'
  import { apiPostInterfaceTree, listUrl } from '../api/interface'
  import MoudleSwtich from './menuBtnMoudle.vue'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    components: { MoudleSwtich },
    mixins: [TableListMixin],
    props: {
      dictOptions: {
        type: Object,
        default: () => ({})
      },
      clientId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        buttonIcons,
        listUrl,
        parentId: 'parentId',
        title: '新增按钮',
        visible: false,
        mode: 'transfer',
        params: {
          menuName: '',
          menuNameEn: '',
          perms: '',
          sort: '',
          apiIds: [],
          menuType: '3',
          parentId: '',
          state: '1',
          isVisible: '1',
          isFrame: '1',
          clientId: ''
        },
        rules: {
          menuName: [
            { required: true, message: '按钮名称不能为空', trigger: 'blur' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符 ', trigger: 'blur' }
          ],
          menuNameEn: [
            { required: true, message: '按钮名称(英文)不能为空', trigger: 'blur' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符 ', trigger: 'blur' }
          ],
          perms: [{ required: true, message: '请输入权限码', trigger: 'blur' }],
          sort: [{ required: true, message: '按钮顺序不能为空', trigger: 'blur' }]
        },
        disableMixinCreated: true,
        currentNode: {},
        toData: [],
        apiTreeData: [],
        checkedKeys: [],
        defaultKeys: [],
        attrOptions: {
          children: 'children',
          label: 'apiName',
          value: 'id'
        },
        btnloading: false
      }
    },
    computed: {
      otherParam() {
        const data = { parentId: this.currentNode?.value ?? '', apiType: 2 }
        return data
      },
      treeOptions() {
        return JSON.parse(JSON.stringify(this.apiTreeData).replace(/"children":\[]/g, '"no":0'))
      }
    },
    created() {
      // this.loadInterfaceTree()
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        this.toData = info.apis ? info.apis : []
        this.$nextTick(() => {
          this.params = Object.assign(this.params, info)
          if (this.params?.apis?.length) {
            this.currentNode = { value: this.params.apis[0].parentId }
            this.loadData()
          }
        })
        this.loadInterfaceTree()

        if (info?.id) {
          this.title = '编辑按钮'
          return
        }
        this.title = '新增按钮'
      },
      loadInterfaceTree() {
        apiPostInterfaceTree({ apiType: 1 }).then(({ code, data }) => {
          if (code === EnumApiCode.Success) {
            this.apiTreeData = data.map((v) => {
              const result = { ...v, parentId: 0 }
              return result
            })
            // if (!this.currentNode.value) {
            //   this.currentNode = this.apiTreeData.length ? this.apiTreeData[0] : {}
            //   this.currentNode.label = this.currentNode.apiName
            //   this.currentNode.value = this.currentNode.id
            // }

            // this.loadData()
          }
        })
      },
      handleResetNode(val) {
        this.currentNode = val
        this.loadData()
      },
      filterIntefaceTreeData(checkedKeys, list) {
        for (let i = 0; i < list.length; i++) {
          if (`${list[i].apiType}` === '2') {
            checkedKeys.push(list[i].id)
          }
          if (list[i].children) {
            checkedKeys = this.filterIntefaceTreeData(checkedKeys, list[i].children)
          }
        }
        return checkedKeys
      },
      renderContentLeft(h, { node }) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
          </span>
        )
      },
      handleSubmit: throttle(function () {
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            this.checkedKeys = this.$refs.apiTransfer?.modeOptions.map((v) => v[this.attrOptions.value])
            const param = {
              ...omit(this.params, 'apis'),
              parentId: this.params.parentId,
              apiIds: this.checkedKeys,
              clientId: this.clientId
            }
            const { code, msg } = 'id' in this.params ? await apiPostEditMenu(param) : await apiPostAddMenu(param)
            if (code === EnumApiCode.Success) {
              this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
              this.$emit('handleSuccess')
              this.handleClose()
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.currentNode = {}
        this.params.apis = []
        this.tableData = []
        this.toData = []
        this.visible = false
      }
    }
  }
</script>
